<template>
  <div class="form-container">
    <el-form inline :model="form" :rules="rules" ref="refRule" class="form-line" status-icon label-width="80">
      <el-form-item label="岗位名称" prop="roleName">
        <el-input size="default" v-model="form.roleName" placeholder="请输入岗位名称"></el-input>
      </el-form-item>
      <el-form-item label="公司类型" prop="companyType">
        <el-select size="default" v-model="form.companyType" placeholder="请选择所属公司类型">
          <el-option v-for="item in companyTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
  <div class="table-container">
    <div class="add-left">
      <div class="add-title">岗位描述</div>
      <el-table border :show-header="false" :cell-style="{ textAlign: 'left', fontSize: '13px' }" :data="reMarkData">
        <el-table-column type="index" width="60"></el-table-column>
        <el-table-column label="描述" prop="description"></el-table-column>
        <el-table-column label="操作" prop="description" width="80">
          <template #default="scope">
            <el-button type="text" size="small" @click="removeRemark(scope.$index)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-table
        border
        :show-header="false"
        :cell-style="{ textAlign: 'left', fontSize: '13px' }"
        :data="[{ id: 1, description: 'string' }]"
      >
        <el-table-column label="描述">
          <el-input
            type="textarea"
            v-model="description.description"
            @keydown.enter.prevent="addDecription"
            placeholder="请输入描述"
          ></el-input>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <el-button type="text" size="small" @click="addDecription">添加</el-button>
        </el-table-column>
      </el-table>
    </div>
    <div class="add-right">
      <div class="add-title">
        权限管理(WEB)
        <!-- <span style="font-size: 12px; color: #999999">(仅供参考，实际权限由管理员配置)</span> -->
        <span><el-checkbox v-model="allChecked" label="web" @change="handleAllChecked">全选</el-checkbox></span>
      </div>
      <el-table
        border
        :header-cell-style="{
          textAlign: 'center',
          fontWeight: '100',
          fontSize: '13px',
          color: 'white',
          backgroundColor: '#009688'
        }"
        :data="newMenuList"
      >
        <el-table-column label="一级分类" width="150">
          <template #default="scope">
            <el-checkbox @change="handleChecked(scope.row)" v-model="scope.row.checked">
              {{ scope.row.meta.title }}
            </el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="二级分类">
          <template #default="scope">
            <el-checkbox
              v-for="item in scope.row.children"
              @change="handleChildrenChecked(scope.row, item.checked)"
              v-model="item.checked"
              :key="item.menuId"
              :label="item.menuId"
            >
              {{ item.meta.title }}
            </el-checkbox>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <div class="btn-container">
    <el-button type="primary">取消</el-button>
    <el-button type="primary" v-if="btnFlag" @click="handleSubmit(refRule as FormInstance)">保存</el-button>
    <el-button type="primary" v-else @click="handleSubmit(refRule as FormInstance)">修改</el-button>
  </div>
</template>

<script setup lang="tsx" name="ProPostAdd">
import { ElMessage, FormInstance } from "element-plus";
import { FormRules } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { Post } from "@/api/interface/province/organizationManage";
import { addPostAPI, postDetailAPI, updatePostAPI, getMenuListAPI } from "@/api/modules/province/organizMangeAPI";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const form = ref<Post.Detail>({
  roleId: 1,
  roleName: "",
  companyType: 1
});
const reMarkData = ref<Post.Description[]>([]);
const refRule = ref<FormInstance>();
const rules = ref<FormRules>({
  roleName: [
    { required: true, message: "请输入岗位名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
  ],
  companyType: [{ required: true, message: "请选择所属公司类型", trigger: "blur" }]
});
let description = ref<Post.Description>({
  id: 0,
  description: "",
  postId: 0
});
const allChecked = ref(false);
const menuList = ref<Post.MenuList[]>([]);
interface companyTypeOptionsType {
  value: number;
  label: string;
}
const companyTypeOptions = reactive<companyTypeOptionsType[]>([
  { value: 1, label: "省级公司" },
  { value: 2, label: "市级公司" }
]);
const decriptionRemake = ref<Post.Description[]>([]);
const addDecription = () => {
  reMarkData.value.push(description.value);
  console.log(reMarkData.value);
  decriptionRemake.value.push(description.value);
  description.value = {
    description: ""
  };
};
const removeRemark = (index: number) => {
  console.log(index);
  reMarkData.value.splice(index, 1);
  decriptionRemake.value.splice(index, 1);
};
let newMenuList = ref<Post.MenuList[]>([]);
let btnFlag = ref<boolean>(true);
onMounted(() => {
  // console.log("执行了");
  getMenuList();
  newMenuList.value = newMenuListFun(menuList.value, false);
  btnFlag.value = true;
  if (route.query.id !== undefined) {
    const id = Number(route.query.id);
    btnFlag.value = false;
    getDetail(id);
  }
});
let addData = ref<Post.PostAdd>({
  detail: {},
  description: [],
  menu: []
});
const newMenuListFun = (menu: Post.MenuList[], bol: boolean = false): Post.MenuList[] => {
  return menu.map(item => {
    return {
      menuId: item.menuId,
      meta: item.meta,
      checked: bol,
      component: item.component,
      path: item.path,
      redirect: item.redirect,
      hidden: item.hidden,
      name: item.name,
      children: item.children.map(child => {
        return {
          menuId: child.menuId,
          meta: item.meta,
          checked: bol,
          component: item.component,
          path: item.path,
          redirect: item.redirect,
          hidden: item.hidden,
          name: item.name
        };
      })
    };
  });
};
const handleAllChecked = (): void => {
  // console.log(allChecked.value);
  newMenuList.value.forEach(item => {
    item.checked = allChecked.value;
    item.children.forEach(child => {
      child.checked = allChecked.value;
    });
  });
};
const handleChecked = (row: Post.MenuList): void => {
  // row.checked = !row.checked;
  row.children.forEach(child => {
    child.checked = row.checked;
  });
};
const handleChildrenChecked = (row: Post.MenuList, checked: boolean) => {
  if (checked) {
    row.checked = true;
  } else {
    row.checked = false;
    row.children.forEach(child => {
      if (child.checked) {
        row.checked = true;
        return;
      }
    });
  }
};
const add = async (row: Post.PostAdd) => {
  const { msg, code } = await addPostAPI(row);
  if (code == "200") {
    ElMessage.success("添加成功");
    router.push({ path: "/provinceLevel/proOrganization/proPost/index" });
  } else {
    ElMessage.error("添加失败" + msg);
  }
};
const update = async (row: Post.PostAdd) => {
  const { msg, code } = await updatePostAPI(row);
  if (code == "200") {
    ElMessage.success("修改成功");
    router.push({ path: "/provinceLevel/proOrganization/proPost/index" });
  } else {
    ElMessage.error("修改失败" + msg);
  }
};
const handleSubmit = (formEl: FormInstance): void => {
  formEl
    .validate()
    .then(() => {
      addData.value.detail = {
        roleName: form.value.roleName,
        province: JSON.parse(localStorage.getItem("userInfo") as string).province,
        companyType: form.value.companyType
      };
      decriptionRemake.value.forEach(item => {
        addData.value.description.push({
          description: item.description as string
        });
      });
      newMenuList.value.forEach(item => {
        if (item.checked) {
          addData.value.menu.push({
            menuId: item.menuId
          });
          item.children.forEach(child => {
            if (child.checked) {
              addData.value.menu.push({
                menuId: child.menuId
              });
            }
          });
        }
      });
      console.log(newMenuList.value);
      if (newMenuList.value.length == 0) {
        ElMessage.error("请选择权限");
        return;
      } else {
        if (btnFlag.value) {
          add(addData.value);
        } else {
          update(addData.value);
        }
      }
    })
    .catch(() => {
      ElMessage.error("请填写正确的信息");
    });
};
const getDetail = async (id: number) => {
  const { data, code, msg } = await postDetailAPI(id);
  if (code == "200" && data) {
    form.value = data.detail;
    reMarkData.value = data.description;
    // console.log(newMenuList.value, newMenuListFun(data.menu, true));
    newMenuList.value = Object.assign(newMenuList.value, newMenuListFun(data.menu, true));
    // console.log(Object.assign(newMenuList.value, newMenuListFun(data.menu, true)));
  } else {
    ElMessage.info(msg);
  }
};
const getMenuList = async () => {
  const { data, code, msg } = await getMenuListAPI({
    companyType: 1
  });
  if (code == "200" && data) {
    menuList.value = data;
    newMenuList.value = newMenuListFun(data, false);
    console.log(newMenuList.value);
  } else {
    ElMessage.info(msg);
  }
};
</script>
<style lang="scss" scoped>
.form-container {
  padding: 10px;
  margin-bottom: 10px;
  background-color: white;
  .el-form {
    display: inline-block;
    ::v-deep .el-form-item__label {
      font-size: 13px;
    }
  }
  .form-line {
    .el-form-item {
      margin: 0;
      margin-right: 20px;
    }
    .el-input {
      width: 240px;
    }
    .el-select {
      width: 240px;
    }
  }
}
.table-container {
  background-color: white;
  .add-left {
    box-sizing: border-box;
    display: inline-block;
    width: 50%;
    padding: 10px;
    vertical-align: top;
  }
  .add-right {
    box-sizing: border-box;
    display: inline-block;
    width: 50%;
    padding: 10px;
    ::v-deep .el-checkbox__label {
      font-size: 13px;
    }
  }
  .add-title {
    margin-bottom: 15px;
    font-size: 13px;
    font-weight: bold;
    color: black;
    span {
      display: inline-block;
      float: right;
      margin-top: -7px;
    }
  }
}
.btn-container {
  padding: 10px;
  text-align: center;
  background-color: white;
  ::v-deep .el-button > span {
    font-size: 13px;
  }
}
</style>
